package com.traffic.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mysql.cj.util.StringUtils;
import com.traffic.annotation.ApiJsonObject;
import com.traffic.annotation.ApiJsonProperty;
import com.traffic.constant.Status;

import com.traffic.entity.Param;
import com.traffic.entity.Rank;
import com.traffic.entity.UserInfo;
import com.traffic.model.ApiResponse;
import com.traffic.model.CalResult;
import com.traffic.service.*;
import com.traffic.util.CalculateUtil;

import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.traffic.service.ParamService;

import javax.swing.plaf.basic.BasicScrollBarUI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Api(tags = "计算参数相关接口")
@RestController
@RequestMapping(value = "/calculate")
@Slf4j
public class CalculateController {

    @Autowired
    private ParamService paramService;

    @Autowired
    private CalculateUtil calUtil;

    @Autowired
    private RankService rankService;

    @Autowired
    private BigdataService bigdataService;

    @Autowired
    private ScoreService scoreService;

    @Autowired
    private UserInfoService userInfoService;

    @ApiOperation(value = "【计算风险得分】", notes = "风险得分")
    @PostMapping("/oldrisk")
    @ApiJsonObject(name = "data",value = {
            @ApiJsonProperty(type =Integer.class,key = "user_id",example = "1" , description = "用户id"),
            @ApiJsonProperty(type =String.class,key = "sex",example = "男" , description = "性别"),
            @ApiJsonProperty(type =Integer.class,key = "age",example = "28" , description = "年龄"),
            @ApiJsonProperty(type =Double.class,key = "maxspeed",example = "61.5" , description = "最高速度"),
            @ApiJsonProperty(type =String.class,key = "attention",example = "专注开车" , description = "注意力:专注开车、接打电话、玩手机"),
            @ApiJsonProperty(type =String.class,key = "rapidturn",example = "触发1" , description = "急转弯：未触发、触发1、触发2、触发3"),
            @ApiJsonProperty(type =String.class,key = "acceleration",example = "未触发" , description = "急加速：未触发、触发1、触发2、触发3"),
            @ApiJsonProperty(type =String.class,key = "nacceleration",example = "触发2" , description = "急减速：未触发、触发1、触发2、触发3"),
            @ApiJsonProperty(type =String.class,key = "road",example = "铺装路面" , description = "路面情况：铺装路面、石子路、坑洼路"),
            @ApiJsonProperty(type =Double.class,key = "angle",example = "8.65" , description = "平均角加速度"),

    })
    public ApiResponse calculateRisk( @RequestBody Map<String, Object> data) {

        List<Param> params=paramService.queryTargetParam("B");
        List<Param> ageParam = paramService.queryTargetParam("age");
        List<Param> speedParam = paramService.queryTargetParam("speed");

        Long userId = new Long(data.get("user_id").toString());

        Rank hisdata = rankService.selectByUserId(userId);

        UserInfo userInfo = userInfoService.getUserInfoByUserId(userId);

        String sex = data.get("sex").toString();
        String age = data.get("age").toString();
        String attention = data.get("attention").toString();
        String maxspeed = data.get("maxspeed").toString();
        String rapidturn = data.get("rapidturn").toString();
        String acceleration =data.get("acceleration").toString();
        String nacceleration =data.get("nacceleration").toString();
        String road = data.get("road").toString();
        String angle = data.get("angle").toString();
        String stationarity = data.get("stationarity").toString();

        Double sexValue = 0.0;
        Double ageValue =0.0;
        Double attentionValue = 0.0;
        Double maxspeedValue = 0.0;
        Double rapidturnValue =0.0;
        Double accelerationValue = 0.0;
        Double naccelerationValue = 0.0;
        Double roadValue = 0.0;
        Double stationarityValue = Double.parseDouble(stationarity);

        Double angleValue = new Double(angle);

        List<Double> Adata = new ArrayList<>();

        List<Double> Bdata = new ArrayList<>();
       // double

        if(userInfo.getSex()==0)sexValue = 0.0;
        else if(userInfo.getSex()==1)sexValue = 1.0;

        Double tage = Double.parseDouble(age);
        if(tage<=ageParam.get(0).getValue() && tage> 0.0)ageValue =1.0;
        else if(tage<=ageParam.get(1).getValue() && tage> ageParam.get(0).getValue())ageValue =2.0;
        else if(tage<=ageParam.get(2).getValue() && tage> ageParam.get(1).getValue())ageValue =3.0;
        else if(tage>ageParam.get(2).getValue())ageValue =4.0;


        if(attention.contains("专注") )attentionValue=0.0;
        else if(attention.contains("接打"))attentionValue=1.0;
        else if(attention.contains("玩"))attentionValue=2.0;

        Double speed= Double.parseDouble(maxspeed);

        if(speed<=speedParam.get(0).getValue())maxspeedValue=0.0;
        else if (speed>speedParam.get(0).getValue() && speed<=speedParam.get(1).getValue())maxspeedValue=1.0;
        else if (speed>speedParam.get(1).getValue() && speed<=speedParam.get(2).getValue())maxspeedValue=2.0;
        else if (speed>speedParam.get(2).getValue() && speed<=speedParam.get(3).getValue())maxspeedValue=3.0;
        else if (speed>speedParam.get(3).getValue() && speed<=speedParam.get(4).getValue())maxspeedValue=4.0;
        else if (speed>speedParam.get(4).getValue())maxspeedValue=5.0;

        if(rapidturn.contains("未触发"))rapidturnValue=0.0;
        else if(rapidturn.contains("触发1"))rapidturnValue=1.0;
        else if(rapidturn.contains("触发2"))rapidturnValue=2.0;
        else if(rapidturn.contains("触发3"))rapidturnValue=3.0;


        if(acceleration.contains("未触发"))accelerationValue=0.0;
        else if(acceleration.contains("触发1"))accelerationValue=1.0;
        else if(acceleration.contains("触发2"))accelerationValue=2.0;
        else if(acceleration.contains("触发3"))accelerationValue=4.0;


        if(nacceleration.contains("未触发"))naccelerationValue=0.0;
        else if(nacceleration.contains("触发1"))naccelerationValue=1.0;
        else if(nacceleration.contains("触发2"))naccelerationValue=2.0;
        else if(nacceleration.contains("触发3"))naccelerationValue=5.0;


        if(road.contains("铺装"))roadValue=0.0;
        else if(road.contains("石子"))roadValue=1.0;
        else if(road.contains("坑洼"))roadValue=2.0;


        Adata.add(sexValue);
        Adata.add(ageValue);
        Adata.add(attentionValue);
        Adata.add(maxspeedValue);
        Adata.add(rapidturnValue);
        Adata.add(accelerationValue);
        Adata.add(naccelerationValue);
        Adata.add(roadValue);


        Bdata.add(hisdata.getMorningTime()/hisdata.getAllTime());
        Bdata.add(hisdata.getAfternoonTime()/hisdata.getAllTime());
        Bdata.add(hisdata.getEveningTime()/hisdata.getAllTime());
        Bdata.add(hisdata.getHisVel());
        Bdata.add(hisdata.getHisAcc());
        Bdata.add(angleValue);
        Bdata.add(hisdata.getHisMileage());
        Bdata.add(stationarityValue);



        Double Agx = Math.abs(calUtil.CalculateRiskScore(Adata,params,8,0));
        List<Double> Ascore = calUtil.SingleScore(Adata,params,8,0);


        Double Bgx = Math.abs(calUtil.CalculateRiskScore(Bdata,params,8,8));
        List<Double> Bscore = calUtil.SingleScore(Bdata,params,8,8);


        Double milex = calUtil.SigmoidFunction(Bscore.get(6)/15+params.get(16).getValue())*100;

        Double sigx = Math.abs(Agx+Bgx)-Bscore.get(6)+milex;

        Double res = calUtil.SigmoidFunction(sigx/25+params.get(16).getValue())*100;

        scoreService.saveScore(Ascore,Bscore,res,userId);
        //scoreService.saveScore(Adata,Bdata,res,userId);

        if (Agx>1)bigdataService.insertTypeData(Adata,0,1,userId);
        else bigdataService.insertTypeData(Adata,1,1,userId);

        if (Bgx>5)bigdataService.insertTypeData(Bdata,1,2,userId);
        else bigdataService.insertTypeData(Bdata,0,2,userId);


      //  CalResult calResult = new CalResult();

       // calResult.setScore(res);

        return ApiResponse.ofStatus(Status.OK,res);
    }


    @ApiOperation(value = "【计算风险得分】", notes = "风险得分")
    @PostMapping("/risk")
    @ApiJsonObject(name = "data",value = {
            @ApiJsonProperty(type =Integer.class,key = "user_id",example = "1" , description = "用户id"),
            @ApiJsonProperty(type =String.class,key = "sex",example = "男" , description = "性别"),
            @ApiJsonProperty(type =Integer.class,key = "age",example = "28" , description = "年龄"),
            @ApiJsonProperty(type =Double.class,key = "maxspeed",example = "61.5" , description = "最高速度"),
            @ApiJsonProperty(type =String.class,key = "attention",example = "专注开车" , description = "注意力:专注开车、接打电话、玩手机"),
            @ApiJsonProperty(type =String.class,key = "rapidturn",example = "触发1" , description = "急转弯：未触发、触发1、触发2、触发3"),
            @ApiJsonProperty(type =String.class,key = "acceleration",example = "未触发" , description = "急加速：未触发、触发1、触发2、触发3"),
            @ApiJsonProperty(type =String.class,key = "nacceleration",example = "触发2" , description = "急减速：未触发、触发1、触发2、触发3"),
            @ApiJsonProperty(type =String.class,key = "road",example = "铺装路面" , description = "路面情况：铺装路面、石子路、坑洼路"),
            @ApiJsonProperty(type =Double.class,key = "angle",example = "8.65" , description = "平均角加速度"),

            @ApiJsonProperty(type =Double.class,key = "time",example = "60" , description = "时间"),
            @ApiJsonProperty(type =Double.class,key = "mileage",example = "2.2" , description = "里程"),
            @ApiJsonProperty(type =Double.class,key = "acc",example = "0.8" , description = "平均急加速：数值"),
            @ApiJsonProperty(type =Double.class,key = "nacc",example = "0.4" , description = "平均急减速：数值"),

            @ApiJsonProperty(type =Double.class,key = "maxacc",example = "0.8" , description = "最大急加速：数值"),
            @ApiJsonProperty(type =Double.class,key = "maxnacc",example = "0.4" , description = "最大急减速：数值"),
            @ApiJsonProperty(type =Double.class,key = "stationary",example = "0.7" , description = "平顺系数")


    })
    public ApiResponse newcalculateRisk( @RequestBody Map<String, Object> data) {

        List<Param> params=paramService.queryTargetParam("B");
        List<Param> ageParam = paramService.queryTargetParam("age");
        List<Param> speedParam = paramService.queryTargetParam("speed");

        Long userId = new Long(data.get("user_id").toString());

        Rank hisdata = rankService.selectByUserId(userId);

        UserInfo userInfo = userInfoService.getUserInfoByUserId(userId);

        String sex = data.get("sex").toString();
        String age = data.get("age").toString();
        String attention = data.get("attention").toString();
        String maxspeed = data.get("maxspeed").toString();
        String rapidturn = data.get("rapidturn").toString();
        String acceleration =data.get("acceleration").toString();
        String nacceleration =data.get("nacceleration").toString();
        String road = data.get("road").toString();
        String angle = data.get("angle").toString();
        String stationary = data.get("stationary").toString();

        String mileage = data.get("mileage").toString();
        String time = data.get("time").toString();

        Double sexValue = 0.0;
        Double ageValue =0.0;
        Double attentionValue = 0.0;
        Double maxspeedValue = 0.0;
        Double rapidturnValue =0.0;
        Double accelerationValue = 0.0;

        Double acc = Double.parseDouble(data.get("acc").toString());
        Double nacc = Double.parseDouble(data.get("nacc").toString());

        Double maxacc = Double.parseDouble(data.get("maxacc").toString());
        Double maxnacc = Double.parseDouble(data.get("maxnacc").toString());

        Double naccelerationValue = 0.0;
        Double roadValue = 0.0;
        Double stationarityValue = Double.parseDouble(stationary);

        Double angleValue = Double.parseDouble(angle);

        Double mileageValue = Double.parseDouble(mileage);
        Double timeValue = Double.parseDouble(time);





        List<Double> Adata = new ArrayList<>();

        List<Double> Bdata = new ArrayList<>();
        // double

        if(userInfo.getSex()==0)sexValue = 0.0;
        else if(userInfo.getSex()==1)sexValue = 1.0;

        Double tage = Double.parseDouble(age);
        if(tage<=ageParam.get(0).getValue() && tage> 0.0)ageValue =1.0;
        else if(tage<=ageParam.get(1).getValue() && tage> ageParam.get(0).getValue())ageValue =2.0;
        else if(tage<=ageParam.get(2).getValue() && tage> ageParam.get(1).getValue())ageValue =3.0;
        else if(tage>ageParam.get(2).getValue())ageValue =4.0;

        if(attention.contains("专注") )attentionValue=0.0;
        else if(attention.contains("接打"))attentionValue=1.0;
        else if(attention.contains("玩"))attentionValue=2.0;

        Double speed= Double.parseDouble(maxspeed);

        if(speed<=speedParam.get(0).getValue())maxspeedValue=0.0;
        else if (speed>speedParam.get(0).getValue() && speed<=speedParam.get(1).getValue())maxspeedValue=1.0;
        else if (speed>speedParam.get(1).getValue() && speed<=speedParam.get(2).getValue())maxspeedValue=2.0;
        else if (speed>speedParam.get(2).getValue() && speed<=speedParam.get(3).getValue())maxspeedValue=3.0;
        else if (speed>speedParam.get(3).getValue() && speed<=speedParam.get(4).getValue())maxspeedValue=4.0;
        else if (speed>speedParam.get(4).getValue())maxspeedValue=5.0;

        if(rapidturn.contains("未触发"))rapidturnValue=0.0;
        else if(rapidturn.contains("触发1"))rapidturnValue=1.0;
        else if(rapidturn.contains("触发2"))rapidturnValue=2.0;
        else if(rapidturn.contains("触发3"))rapidturnValue=3.0;


        if(acceleration.contains("未触发"))accelerationValue=0.0;
        else if(acceleration.contains("触发1"))accelerationValue=1.0;
        else if(acceleration.contains("触发2"))accelerationValue=2.0;
        else if(acceleration.contains("触发3"))accelerationValue=4.0;


        if(nacceleration.contains("未触发"))naccelerationValue=0.0;
        else if(nacceleration.contains("触发1"))naccelerationValue=1.0;
        else if(nacceleration.contains("触发2"))naccelerationValue=2.0;
        else if(nacceleration.contains("触发3"))naccelerationValue=5.0;

        if(road.contains("铺装"))roadValue=0.0;
        else if(road.contains("石子"))roadValue=1.0;
        else if(road.contains("坑洼"))roadValue=2.0;

        Adata.add(sexValue);
        Adata.add(ageValue);
        Adata.add(attentionValue);
        Adata.add(maxspeedValue);
        Adata.add(rapidturnValue);
        Adata.add(accelerationValue);
        Adata.add(naccelerationValue);
        Adata.add(roadValue);


        Bdata.add(hisdata.getMorningTime()/hisdata.getAllTime());
        Bdata.add(hisdata.getAfternoonTime()/hisdata.getAllTime());
        Bdata.add(hisdata.getEveningTime()/hisdata.getAllTime());
        Bdata.add(hisdata.getHisVel());
        Bdata.add(hisdata.getHisAcc());
        Bdata.add(angleValue);
        Bdata.add(hisdata.getHisMileage());
        Bdata.add(stationarityValue);

        Double alltime = hisdata.getAllTime()+timeValue;
        hisdata.setHisMileage(hisdata.getHisMileage()+mileageValue);
        hisdata.setHisAcc((hisdata.getHisAcc()*hisdata.getAllTime()+acc*timeValue)/alltime);
        hisdata.setHisNAcc((hisdata.getHisNAcc()*hisdata.getAllTime()+nacc*timeValue)/alltime);
        hisdata.setAllTime(alltime);
        hisdata.setHisVel(hisdata.getHisMileage()*3600/hisdata.getAllTime());

        hisdata.setStationarity((hisdata.getStationarity()*hisdata.getStatimes()+stationarityValue)/(hisdata.getStatimes()+1));
        hisdata.setStatimes(hisdata.getStatimes()+1);

        if(hisdata.getMaxAcc()<maxacc)hisdata.setMaxAcc(maxacc);
        if(hisdata.getMaxNAcc()<maxnacc)hisdata.setMaxNAcc(maxnacc);
        if(hisdata.getMaxVel()<speed)hisdata.setMaxVel(speed);





        Double Agx = Math.abs(calUtil.CalculateRiskScore(Adata,params,8,0));
        List<Double> Ascore = calUtil.SingleScore(Adata,params,8,0);


        Double Bgx = Math.abs(calUtil.CalculateRiskScore(Bdata,params,8,8));
        List<Double> Bscore = calUtil.SingleScore(Bdata,params,8,8);


        Double milex = calUtil.SigmoidFunction(Bscore.get(6)/25+params.get(16).getValue())*100;

        Double sigx = Math.abs(Agx+Bgx)-Bscore.get(6)+milex;

        Double res = calUtil.SigmoidFunction(sigx/25+params.get(16).getValue())*100;

        Double score = calUtil.SigmoidFunction(Agx/5+params.get(16).getValue())*100;
        Double allscore = calUtil.SigmoidFunction(Bgx/35+params.get(16).getValue())*100;

        //scoreService.saveScore(Ascore,Bscore,res,userId);
        scoreService.saveScore(Adata,Bdata,res,userId);
        hisdata.setScore(allscore);

        if (Agx>1)bigdataService.insertTypeData(Adata,0,1,userId);
        else bigdataService.insertTypeData(Adata,1,1,userId);

        if (Bgx>5)bigdataService.insertTypeData(Bdata,1,2,userId);
        else bigdataService.insertTypeData(Bdata,0,2,userId);


        CalResult calResult = new CalResult();

         calResult.setScore(score.toString());
         calResult.setTime(hisdata.getAllTime().toString());
         calResult.setMaxacc(hisdata.getMaxAcc().toString());
         calResult.setAveacc(hisdata.getHisAcc().toString());
         calResult.setMaxspeed(hisdata.getMaxVel().toString());
         calResult.setAvespeed(hisdata.getHisVel().toString());
         calResult.setMileage(hisdata.getHisMileage().toString());

        calResult.setMaxnacc(hisdata.getMaxNAcc().toString());
        calResult.setAvenacc(hisdata.getHisNAcc().toString());


        calResult.setAllscore(allscore.toString());
        calResult.setStationary(hisdata.getStationarity().toString());

        rankService.updateById(hisdata);

        return ApiResponse.ofStatus(Status.OK,calResult);
    }




}
